<template>
  <el-form :model="account"
           :rules="rules"
           ref="account">
    <el-form-item>
      <h1>登录</h1>
    </el-form-item>
    <el-form-item class="input-row"
                  prop="username">
      <el-input name="username"
                placeholder="请输入用户名"
                prefix-icon="iconfont icon-user"
                type="text"
                v-model="account.username"
                @keyup.enter.native="loginHandle"
                clearable />
    </el-form-item>
    <el-form-item prop="password"
                  class="input-row">
      <el-input name="password"
                placeholder="请输入密码"
                prefix-icon="iconfont icon-unlock"
                type="password"
                v-model="account.password"
                @keyup.enter.native="loginHandle"
                clearable />
    </el-form-item>
    <el-form-item class="check-row">
      <el-checkbox v-model="rememberPwd"
                   :checked="rememberPwd">记住密码</el-checkbox>
    </el-form-item>
    <el-form-item class="btn-row">
      <el-button class="btn"
                 :loading="loading"
                 @click="loginHandle">
        登录
      </el-button>
    </el-form-item>
    <el-form-item class="text-row">
      没有账号？现在<a class="link-btn"
         @click="()=>{this.$emit('switch',false)}">注册</a>
    </el-form-item>
    <el-form-item class="btn-row">
      <el-button class="btn code-btn"
                 @click="$router.push('/coder')">
        <i class="iconfont">&#xe767;</i> 直接去编程 ==>
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { _debounce } from '@/utils/debounce'
// import { encodeMD5 } from '@/utils/encryption'
import { getCookie, setCookie, clearCookie } from './cookie'
import { mapGetters } from 'vuex'
export default {
  data () {
    return {
      loading: false,
      rememberPwd: Boolean(localStorage.getItem('rememberPwd')) || false,
      account: {
        username: localStorage.getItem('username') || '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 10, message: '用户名长度在4-10个字符', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['token', 'nickname'])
  },
  created () {
    if (this.rememberPwd) { this.account.password = getCookie() }
  },
  methods: {
    loginHandle: _debounce(function () {
      this.loading = true
      this.$refs.account.validate((valid) => {
        if (valid) {
          if (this.token) {
            this.loading = false
            this.$notify.error({
              title: '错误',
              message: '请勿重复登录！',
              position: 'bottom-right'
            })
          } else {
            // this.account.password = encodeMD5(this.account.password)
            // console.log(this.account.password)
            this.$store.dispatch('user/login', this.account)
              .then((res) => {
                // console.log(res)
                this.loading = false
                if (res.token) {
                  if (this.rememberPwd) {
                    setCookie(this.account.password)
                  } else { clearCookie() }
                  // 存入localStorage时变为字符串，'true'或'false'都为true
                  localStorage.setItem('rememberPwd', this.rememberPwd ? 'true' : '')
                  localStorage.setItem('username', this.account.username)
                  this.$notify.success({
                    title: '成功',
                    message: `${this.nickname}，欢迎回来！`,
                    position: 'bottom-right'
                  })
                  this.$router.push('/problems')
                } else {
                  if ('error' in res) {
                    this.$notify.error({
                      title: '错误',
                      message: res.error,
                      position: 'bottom-right'
                    })
                    this.account.password = ''
                  } else {
                    this.$notify.error({
                      title: '错误',
                      message: '登录失败，请稍后再试！',
                      position: 'bottom-right'
                    })
                    this.account.password = ''
                  }
                }
              })
          }
        } else { this.loading = false }
      })
    }, 300)
  }
}
</script>

<style lang="stylus" scoped>
@import './index.styl'
</style>
